const {remote, app, clipboard, getAppPath} = require('electron');
const projectRoot = remote.getGlobal('projectPath');
const srcPath = remote.getGlobal('srcPath');

const {dialog} = remote;

const core = require(`${srcPath}/mainlib/core`);
const Type = require(`${srcPath}/mainlib/type`);
const {animation_support} = require(`${srcPath}/mainlib/window-animation`);
const ipc = require(`${srcPath}/mainlib/ipc`);
const regeditTools = require('regedit');
const path = require('path');

if(core.isInAsar()) {
    regeditTools.setExternalVBSLocation(path.dirname(projectRoot) + '/node_modules/regedit/vbs');
}

const TEXT = {
    AUTOSTART_NO: '未设置自动启动',
    AUTOSTART_YES: '已设置自动启动',
    AUTOSTART_ERR: '检查失败'
};


const status = {
    AUTOSTART_NO_CHECK:0,
    AUTOSTART_YES:1,
    AUTOSTART_UNSET:2,
    AUTOSTART_ERR:3,
    AUTOSTART_CHECKING:4,
};

var t = new Vue({
    el:'#root',
    
    data: {
        content: 'base',
        setting: core.getSetting(),
        
        dlg: {
            newDirectory: {
            }
        },
        
        oldSettingString:null,
        
        directoryDepthLabel: {
            '-1': '全部',
            0: '直接子目录和子文件',
            1: '1层',
            2: '2层',
            3: '3层',
            4: '4层',
            5: '5层',
            6: '6层',
            7: '7层',
            8: '8层',
            9: '9层',
            10: '10层',
        },
        
        loadings: {
            checkAutoStart: false
        },
        
        status: {
            autoStart: status.AUTOSTART_NO_CHECK
        }
    },
    
    mounted() {
        this.loadSetting();
        let currentWindow = remote.getCurrentWindow();
        // currentWindow.setMenu(null);
        
        currentWindow.on("show", () => {
            this.content = 'base';
            this.loadSetting();
        });
    
        this.checkAutoStart();
    },
    
    methods: {
        loadSetting() {
            this.setting = core.getSetting();
            this.oldSettingString = JSON.stringify(this.setting);
        },
        
        choiceDirectory() {
            return dialog.showOpenDialogSync({ properties: ['openDirectory'] });
        },
        
        /**
         * 检查自动开启设置
         */
        checkAutoStart() {
            this.status.autoStart = status.AUTOSTART_CHECKING;
            let key1 = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
            let key2 = 'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
            
            regeditTools.list([key1,key2],
                (e,a) => {
                    if(e) {
                        return;
                    }
                    
                    let getexecpath = (cmd) => {
                        cmd = cmd.trim();
                        
                        if(cmd[0] == '"') {
                            cmd = cmd.substr(1).replace(/".*/, '');
                        } else {
                            cmd = cmd.replace(/ .*/, '');
                        }
                        
                        cmd = core.correctPath(cmd);
                        return cmd;
                    };
                    
                    let check = (data) => {
                        let execPath = core.correctPath(process.execPath);
                        
                        for(let key in data.values) {
                            let value = data.values[key].value;
                            let type = data.values[key].type;
                            
                            if(type == 'REG_SZ') {
                                let path = getexecpath(value);
                                
                                if(path == execPath) {
                                    return true;
                                }
                            }
                        }
                        
                        return false;
                    };
                    
                    let result = check(a[key1]);
                    
                    if(result) {
                        this.status.autoStart = status.AUTOSTART_YES;
                        return;
                    }
                    
                    result = check(a[key2]);
                    
                    if(result) {
                        this.status.autoStart = status.AUTOSTART_YES;
                    } else {
                        this.status.autoStart = status.AUTOSTART_UNSET;
                    }
                }
            )
        },
        
        /**
         * 设置开机自动启动
         */
        setAutoStart() {
            regeditTools.putValue({
                'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run': {
                    'JinkoQuickStart': {
                        type:'REG_SZ',
                        value: process.execPath.indexOf(' ') == -1 ? process.execPath : `"${process.execPath}"`
                    }
                }
            }, e => {
                if(e) {
                    alert('设置失败: '+ e.message);
                }
                
                this.checkAutoStart();
            });
        },
        
        /**
         * 取消开机自动启动
         */
        unsetAutoStart() {
            regeditTools.putValue({
                'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run': {
                    'JinkoQuickStart': {
                        type:'REG_SZ',
                        value: ''
                    }
                }
            }, e => {
                if(e) {
                    alert('取消设置失败: '+ e.message);
                }
                
                this.checkAutoStart();
            });
        },
        
        close() {
            let win = animation_support(remote.getCurrentWindow());
            win.hideWithAnimation();
        },
        
        closeEvent(e) {
            e.preventDefault();
            this.close();
        },
        
        isContent(content) {
            return content == this.content;
        },
        
        save() {
            if(this.applySetting()) {
                this.close();
            }
        },
        
        applySetting() {
            try {
                core.saveSetting(this.setting);
                this.oldSettingString = JSON.stringify(this.setting);
            } catch (e) {
                alert('保存失败：' + e.message);
                return false;
            }
            
            core.trigger(core.ET.SETTING_CHANGE);
            this.settingChange();
            return true;
        },
        
        settingChange() {
            remote.getCurrentWindow().setAlwaysOnTop(this.setting.base.nohide);
        },
        
        deleteItem(obj, index) {
            this.$delete(obj, index);
        },
        
        editDirectory(index, item) {
            let edit = Type.clone(item);
            edit = Type.isSimpleObject(edit) ? edit : {
                index: null,
                depth: 0,
                allow_extnames: '',
                ignore_extnames: '',
            };
    
            index = Type.isUndefined(index) ? null : index;
            edit.allow_extnames = this.formatExtnames(edit.allow_extnames).replace(/\|/g, "\n");
            edit.ignore_extnames = this.formatExtnames(edit.ignore_extnames).replace(/\|/g, "\n");
    
            edit.index = index;
            this.dlg.newDirectory = edit;
            this.$refs.dlgAddDirectory.show();
        },
        
        splitExtnames(extname) {
            extname = extname.trim();
            
            if('' == extname) {
                return [];
            }
            
            return this.formatExtnames(extname).split('|');
        },
        
        formatExtnames(str) {
            return str
                .trim()
                .replace(/[\s,;]/g, '|')
                .replace(/\|+/g, '|')
            ;
        },
    
        saveDirectory() {
            let index = this.dlg.newDirectory.index;
            let item = Type.clone(this.dlg.newDirectory);
            item.index = null;
            
            item.allow_extnames = this.formatExtnames(item.allow_extnames);
            item.ignore_extnames = this.formatExtnames(item.ignore_extnames);
            
            if(index === null) {
                this.setting.directories.push(item)
            } else {
                this.setting.directories.splice(index, 1, item);
            }
    
            this.$refs.dlgAddDirectory.hide();
        }
    },
    
    computed: {
        settingChanged() {
            return this.oldSettingString != JSON.stringify(this.setting);
        },
        
        STATUS() {
            return status;
        }
    },
    
});
